<!DOCTYPE html>
<html>
<head>
    

    

    
<!-- Baidu Tongji -->
<script>var _hmt = _hmt || []</script>
<script async src="//hm.baidu.com/hm.js?a7c05ce530152d9866930ef4850ee566"></script>
<!-- End Baidu Tongji -->




    <meta charset="utf-8">
    
    
    
    <title>Mybatis快速入门六(一级缓存) | 神奇的鸭鸭の码农库 | 新知识要不断的总结记录成笔记，要多写，多画，能够清晰透彻的将知识讲给别人听，才是达到理解的层次。</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    
    <meta name="theme-color" content="#765959">
    
    
    <meta name="keywords" content="SSM">
    <meta name="description" content="一级缓存本文学习自： 《深入理解mybatis原理》 MyBatis的一级缓存实现详解 及使用注意事项 一级缓存是Session回话级别的缓存，位于表示一次数据库会话的SqlSession对象中，又称为本地缓存。一级缓存是MyBatis内部实现的一个特性，用户不能配置，默认情况下自动支持缓存，用户没有定制它的权限(不过这也不是绝对的，可以通过开发插件对它进行修改)。 MyBatis会在表示会话的S">
<meta name="keywords" content="SSM">
<meta property="og:type" content="article">
<meta property="og:title" content="Mybatis快速入门六(一级缓存)">
<meta property="og:url" content="http://magic_duck.oschina.io/2017/08/15/Mybatis_primary_06/index.html">
<meta property="og:site_name" content="神奇的鸭鸭の码农库">
<meta property="og:description" content="一级缓存本文学习自： 《深入理解mybatis原理》 MyBatis的一级缓存实现详解 及使用注意事项 一级缓存是Session回话级别的缓存，位于表示一次数据库会话的SqlSession对象中，又称为本地缓存。一级缓存是MyBatis内部实现的一个特性，用户不能配置，默认情况下自动支持缓存，用户没有定制它的权限(不过这也不是绝对的，可以通过开发插件对它进行修改)。 MyBatis会在表示会话的S">
<meta property="og:image" content="http://om6odecqr.bkt.clouddn.com/mybatis%E7%BC%93%E5%AD%98%E6%9C%BA%E5%88%B6">
<meta property="og:image" content="http://om6odecqr.bkt.clouddn.com/%E4%B8%80%E7%BA%A7%E7%BC%93%E5%AD%98%E6%98%AF%E6%80%8E%E6%A0%B7%E7%BB%84%E7%BB%87">
<meta property="og:updated_time" content="2017-12-05T10:18:12.988Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Mybatis快速入门六(一级缓存)">
<meta name="twitter:description" content="一级缓存本文学习自： 《深入理解mybatis原理》 MyBatis的一级缓存实现详解 及使用注意事项 一级缓存是Session回话级别的缓存，位于表示一次数据库会话的SqlSession对象中，又称为本地缓存。一级缓存是MyBatis内部实现的一个特性，用户不能配置，默认情况下自动支持缓存，用户没有定制它的权限(不过这也不是绝对的，可以通过开发插件对它进行修改)。 MyBatis会在表示会话的S">
<meta name="twitter:image" content="http://om6odecqr.bkt.clouddn.com/mybatis%E7%BC%93%E5%AD%98%E6%9C%BA%E5%88%B6">
    
    <link rel="shortcut icon" href="/favicon.ico">
    <link rel="stylesheet" href="/css/style.css?v=1.4.3">
    <script>window.lazyScripts=[]</script>
</head>

<body>
    <div id="loading" class="active"></div>

    <aside id="menu" class="hide" >
  <div class="inner flex-row-vertical">
    <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menu-off">
        <i class="icon icon-lg icon-close"></i>
    </a>
    <div class="brand-wrap">
      <div class="brand">
        <a href="/" class="avatar waves-effect waves-circle waves-light">
          <img src="/img/avatar.jpg">
        </a>
        <hgroup class="introduce">
          <h5 class="nickname">神奇的鸭鸭</h5>
          <a href="mailto:702038338@qq.com" title="702038338@qq.com" class="mail">702038338@qq.com</a>
        </hgroup>
      </div>
    </div>
    <div class="scroll-wrap flex-col">
      <ul class="nav">
        
            <li class="waves-block waves-effect">
              <a href="/"  >
                <i class="icon icon-lg icon-home"></i>
                主页
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/archives"  >
                <i class="icon icon-lg icon-archives"></i>
                归档
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/tags"  >
                <i class="icon icon-lg icon-tags"></i>
                标签
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://git.oschina.net/magic_duck" target="_blank" >
                <i class="icon icon-lg icon-gg-circle"></i>
                码云
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://www.zhihu.com/people/shen-qi-de-ya-ya" target="_blank" >
                <i class="icon icon-lg icon-twitter"></i>
                知乎
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/404.html"  >
                <i class="icon icon-lg icon-link"></i>
                404页面测试
              </a>
            </li>
        
      </ul>
    </div>
  </div>
</aside>

    <main id="main">
        <header class="top-header" id="header">
    <div class="flex-row">
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light on" id="menu-toggle">
          <i class="icon icon-lg icon-navicon"></i>
        </a>
        <div class="flex-col header-title ellipsis">Mybatis快速入门六(一级缓存)</div>
        
        <div class="search-wrap" id="search-wrap">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="back">
                <i class="icon icon-lg icon-chevron-left"></i>
            </a>
            <input type="text" id="key" class="search-input" autocomplete="off" placeholder="输入感兴趣的关键字">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="search">
                <i class="icon icon-lg icon-search"></i>
            </a>
        </div>
        
        
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menuShare">
            <i class="icon icon-lg icon-share-alt"></i>
        </a>
        
    </div>
</header>
<header class="content-header post-header">

    <div class="container fade-scale">
        <h1 class="title">Mybatis快速入门六(一级缓存)</h1>
        <h5 class="subtitle">
            
                <time datetime="2017-08-15T08:07:00.000Z" itemprop="datePublished" class="page-time">
  2017-08-15
</time>


            
        </h5>
    </div>

    

</header>


<div class="container body-wrap">
    
    <aside class="post-widget">
        <nav class="post-toc-wrap" id="post-toc">
            <h4>TOC</h4>
            <ol class="post-toc"><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#一级缓存"><span class="post-toc-number">1.</span> <span class="post-toc-text">一级缓存</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#测试代码"><span class="post-toc-number">1.1.</span> <span class="post-toc-text">测试代码</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#MyBatis中的一级缓存是怎样组织的"><span class="post-toc-number">1.2.</span> <span class="post-toc-text">MyBatis中的一级缓存是怎样组织的</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#一级缓存的工作流程"><span class="post-toc-number">1.3.</span> <span class="post-toc-text">一级缓存的工作流程</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#一级缓存的生命周期"><span class="post-toc-number">1.4.</span> <span class="post-toc-text">一级缓存的生命周期</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#CacheKey的hashcode生成算法"><span class="post-toc-number">1.5.</span> <span class="post-toc-text">CacheKey的hashcode生成算法</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#使用一级缓存需要注意的问题"><span class="post-toc-number">1.6.</span> <span class="post-toc-text">使用一级缓存需要注意的问题</span></a></li></ol></li></ol>
        </nav>
    </aside>
    
<article id="post-Mybatis_primary_06"
  class="post-article article-type-post fade" itemprop="blogPost">

    <div class="post-card">
        <h1 class="post-card-title">Mybatis快速入门六(一级缓存)</h1>
        <div class="post-meta">
            <time class="post-time" title="2017年08月15日 16:07" datetime="2017-08-15T08:07:00.000Z"  itemprop="datePublished">2017-08-15</time>

            


            
<span id="busuanzi_container_page_pv" title="文章总阅读量" style='display:none'>
    <i class="icon icon-eye icon-pr"></i><span id="busuanzi_value_page_pv"></span>
</span>


            

        </div>
        <div class="post-content" id="post-content" itemprop="postContent">
            <h2 id="一级缓存"><a href="#一级缓存" class="headerlink" title="一级缓存"></a>一级缓存</h2><p>本文学习自： <a href="http://blog.csdn.net/luanlouis/article/details/41280959" target="_blank" rel="external">《深入理解mybatis原理》 MyBatis的一级缓存实现详解 及使用注意事项</a></p>
<p><strong>一级缓存是Session回话级别的缓存</strong>，位于表示一次数据库会话的SqlSession对象中，又称为本地缓存。一级缓存是MyBatis内部实现的一个特性，用户不能配置，默认情况下自动支持缓存，用户没有定制它的权限(不过这也不是绝对的，可以通过开发插件对它进行修改)。</p>
<p>MyBatis会在表示会话的SqlSession对象中建立一个简单的缓存，将每次查询到的结果结果缓存起来，当下次查询的时候，如果判断先前有个完全一样的查询，会直接从缓存中直接将结果取出，返回给用户，不需要再进行一次数据库查询了。</p>
<p><strong>MyBatis中一级缓存和二级缓存的组织如下图所示：</strong></p>
<p><img src="http://om6odecqr.bkt.clouddn.com/mybatis%E7%BC%93%E5%AD%98%E6%9C%BA%E5%88%B6" alt="mybatis缓存机制"></p>
<h3 id="测试代码"><a href="#测试代码" class="headerlink" title="测试代码"></a>测试代码</h3><p>通过测试代码你可以看到：</p>
<p>1、第一次发起查询用户id为1的用户信息，先去找缓存中是否有id为1的用户信息，如果没有，从数据库查询用户信息。<br>得到用户信息，将用户信息存储到一级缓存中。</p>
<p>2、如果sqlSession去执行commit操作（执行插入、更新、删除），清空SqlSession中的一级缓存，这样做的目的为了让缓存中存储的是最新的信息，避免脏读。</p>
<p>3、第二次发起查询用户id为1的用户信息，先去找缓存中是否有id为1的用户信息，缓存中有，直接从缓存中获取用户信息。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// 测试1</span></div><div class="line"><span class="meta">@Test</span></div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testOneLevelCache</span><span class="params">()</span> </span>&#123;</div><div class="line">    SqlSession session = sqlSessionFactory.openSession();</div><div class="line">    UserMapper mapper = session.getMapper(UserMapper.class);</div><div class="line">    </div><div class="line">    <span class="comment">// 第一次查询ID为1的用户，去缓存找，找不到就去查找数据库</span></div><div class="line">    User user1 = mapper.findUserById(<span class="number">1</span>);</div><div class="line">    System.out.println(user1);</div><div class="line">    <span class="comment">// 第二次查询ID为1的用户</span></div><div class="line">    User user2 = mapper.findUserById(<span class="number">1</span>);</div><div class="line">    System.out.println(user2);</div><div class="line">    session.close();</div><div class="line">&#125;</div><div class="line"><span class="comment">/*</span></div><div class="line"><span class="comment">DEBUG [main] - ==&gt;  Preparing: SELECT * FROM user WHERE id = ?; </span></div><div class="line"><span class="comment">DEBUG [main] - ==&gt; Parameters: 1(Integer)</span></div><div class="line"><span class="comment">DEBUG [main] - &lt;==      Total: 1</span></div><div class="line"><span class="comment">User [id=1, username=王五, sex=2, birthday=Thu Jul 10 00:00:00 CST 2014, address=null, orders=null]</span></div><div class="line"><span class="comment">User [id=1, username=王五, sex=2, birthday=Thu Jul 10 00:00:00 CST 2014, address=null, orders=null]</span></div><div class="line"><span class="comment">*/</span></div><div class="line"></div><div class="line"><span class="comment">// 测试2</span></div><div class="line"><span class="meta">@Test</span></div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testOneLevelCache2</span><span class="params">()</span> </span>&#123;</div><div class="line">    SqlSession session = sqlSessionFactory.openSession();</div><div class="line">    UserMapper mapper = session.getMapper(UserMapper.class);</div><div class="line">    </div><div class="line">    <span class="comment">// 第一次查询ID为1的用户，去缓存找，找不到就去查找数据库</span></div><div class="line">    User user1 = mapper.findUserById(<span class="number">1</span>);</div><div class="line">    System.out.println(user1);</div><div class="line">    </div><div class="line">    User user = <span class="keyword">new</span> User();</div><div class="line">    user.setUsername(<span class="string">"新成员"</span>);</div><div class="line">    user.setAddress(<span class="string">"陆丰人"</span>);</div><div class="line">    <span class="comment">// 执行增删改操作，会清空一级缓存，这样做的目的为了让缓存中存储的是最新的信息，避免脏读。</span></div><div class="line">    mapper.insertUser(user);</div><div class="line">    </div><div class="line">    <span class="comment">// 第二次查询ID为1的用户</span></div><div class="line">    User user2 = mapper.findUserById(<span class="number">1</span>);</div><div class="line">    System.out.println(user2);</div><div class="line">    session.close();</div><div class="line">&#125;</div><div class="line"><span class="comment">/*</span></div><div class="line"><span class="comment">DEBUG [main] - ==&gt;  Preparing: SELECT * FROM user WHERE id = ?; </span></div><div class="line"><span class="comment">DEBUG [main] - ==&gt; Parameters: 1(Integer)</span></div><div class="line"><span class="comment">DEBUG [main] - &lt;==      Total: 1</span></div><div class="line"><span class="comment">User [id=1, username=王五, sex=2, birthday=Thu Jul 10 00:00:00 CST 2014, address=null, orders=null]</span></div><div class="line"><span class="comment">DEBUG [main] - ==&gt;  Preparing: insert into user (username,birthday,sex,address) values(?,?,?,?); </span></div><div class="line"><span class="comment">DEBUG [main] - ==&gt; Parameters: 新成员(String), null, null, 陆丰人(String)</span></div><div class="line"><span class="comment">DEBUG [main] - &lt;==    Updates: 1</span></div><div class="line"><span class="comment">DEBUG [main] - ==&gt;  Preparing: select last_insert_id(); </span></div><div class="line"><span class="comment">DEBUG [main] - ==&gt; Parameters: </span></div><div class="line"><span class="comment">DEBUG [main] - &lt;==      Total: 1</span></div><div class="line"><span class="comment">DEBUG [main] - ==&gt;  Preparing: SELECT * FROM user WHERE id = ?; </span></div><div class="line"><span class="comment">DEBUG [main] - ==&gt; Parameters: 1(Integer)</span></div><div class="line"><span class="comment">DEBUG [main] - &lt;==      Total: 1</span></div><div class="line"><span class="comment">User [id=1, username=王五, sex=2, birthday=Thu Jul 10 00:00:00 CST 2014, address=null, orders=null]</span></div><div class="line"><span class="comment">*/</span></div></pre></td></tr></table></figure></p>
<h3 id="MyBatis中的一级缓存是怎样组织的"><a href="#MyBatis中的一级缓存是怎样组织的" class="headerlink" title="MyBatis中的一级缓存是怎样组织的"></a>MyBatis中的一级缓存是怎样组织的</h3><p>由于MyBatis使用SqlSession对象表示一次数据库的会话，那么，对于会话级别的一级缓存也应该是在SqlSession中控制的。</p>
<p>事实上SqlSession将它的工作交给了Executor执行器来完成，负责对数据库的各种操作，创建一个SqlSession对象时，MyBatis会为这个SqlSession对象创建一个新的Executor执行器，而缓存信息就被维护在这个Executor执行器中，Mybatis将缓存和对缓存相关的操作封装成了Cache接口中，其关系图如下：<br><img src="http://om6odecqr.bkt.clouddn.com/%E4%B8%80%E7%BA%A7%E7%BC%93%E5%AD%98%E6%98%AF%E6%80%8E%E6%A0%B7%E7%BB%84%E7%BB%87" alt=""><br>如上述的类图所示，Executor接口的实现类BaseExecutor中拥有一个Cache接口的实现类PerpetualCache，则对于BaseExecutor对象而言，它将使用PerpetualCache对象维护缓存。</p>
<h3 id="一级缓存的工作流程"><a href="#一级缓存的工作流程" class="headerlink" title="一级缓存的工作流程"></a>一级缓存的工作流程</h3><ul>
<li>对于某个查询，根据statementId,params,rowBounds来构建一个key值，根据这个key值去缓存Cache中取出对应的key值存储的缓存结果；</li>
<li>判断从Cache中根据特定的key值取的数据数据是否为空，即是否命中；</li>
<li>如果命中，则直接将缓存结果返回；</li>
<li>如果没命中：<ul>
<li>去数据库中查询数据，得到查询结果；</li>
<li>将key和查询到的结果分别作为key,value对存储到Cache中；</li>
<li>将查询结果返回；</li>
</ul>
</li>
<li>结束。</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div><div class="line">73</div><div class="line">74</div><div class="line">75</div><div class="line">76</div><div class="line">77</div><div class="line">78</div><div class="line">79</div><div class="line">80</div><div class="line">81</div><div class="line">82</div><div class="line">83</div><div class="line">84</div><div class="line">85</div><div class="line">86</div><div class="line">87</div><div class="line">88</div><div class="line">89</div><div class="line">90</div><div class="line">91</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// 测试类：</span></div><div class="line">User user1 = mapper.findUserById(<span class="number">1</span>);<span class="comment">// debug入口</span></div><div class="line"></div><div class="line"><span class="comment">// 走openSession-&gt;DefaultSqlSession：</span></div><div class="line"><span class="meta">@Override</span></div><div class="line"><span class="keyword">public</span> &lt;E&gt; <span class="function">List&lt;E&gt; <span class="title">selectList</span><span class="params">(String statement, Object parameter, RowBounds rowBounds)</span> </span>&#123;</div><div class="line">    <span class="keyword">try</span> &#123;</div><div class="line">        <span class="comment">// 从全局配置文件得到映射的statement</span></div><div class="line">        MappedStatement ms = configuration.getMappedStatement(statement);</div><div class="line">        <span class="comment">// 将工作交给Executor执行器：org.apache.ibatis.executor.CachingExecutor@31f9b85e</span></div><div class="line">        <span class="keyword">return</span> executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER);</div><div class="line">    &#125; <span class="keyword">catch</span> (Exception e) &#123;</div><div class="line">        <span class="keyword">throw</span> ExceptionFactory.wrapException(<span class="string">"Error querying database.  Cause: "</span> + e, e);</div><div class="line">    &#125; <span class="keyword">finally</span> &#123;</div><div class="line">        ErrorContext.instance().reset();</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="comment">// 走executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER);</span></div><div class="line">  <span class="meta">@Override</span></div><div class="line"><span class="keyword">public</span> &lt;E&gt; <span class="function">List&lt;E&gt; <span class="title">query</span><span class="params">(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler)</span> <span class="keyword">throws</span> SQLException </span>&#123;</div><div class="line">    <span class="comment">// 应该是处理SQL语句的类</span></div><div class="line">    BoundSql boundSql = ms.getBoundSql(parameterObject);</div><div class="line">    <span class="comment">// 通过算法得到唯一的key</span></div><div class="line">    CacheKey key = createCacheKey(ms, parameterObject, rowBounds, boundSql);</div><div class="line">    <span class="keyword">return</span> query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="comment">// 走query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);</span></div><div class="line"><span class="meta">@Override</span></div><div class="line"><span class="keyword">public</span> &lt;E&gt; <span class="function">List&lt;E&gt; <span class="title">query</span><span class="params">(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql)</span></span></div><div class="line"><span class="function">    <span class="keyword">throws</span> SQLException </span>&#123;</div><div class="line">    <span class="comment">// Cache时二级缓存，不开即null</span></div><div class="line">    Cache cache = ms.getCache();</div><div class="line">    <span class="keyword">if</span> (cache != <span class="keyword">null</span>) &#123;</div><div class="line">        flushCacheIfRequired(ms);</div><div class="line">        <span class="keyword">if</span> (ms.isUseCache() &amp;&amp; resultHandler == <span class="keyword">null</span>) &#123;</div><div class="line">        ensureNoOutParams(ms, parameterObject, boundSql);</div><div class="line">        <span class="meta">@SuppressWarnings</span>(<span class="string">"unchecked"</span>)</div><div class="line">        <span class="comment">// 二级缓存会通过key去查询是否存在，如果没找到就委托基本执行器BaseExecutor去查询：</span></div><div class="line">        <span class="comment">// delegate.&lt;E&gt; query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);</span></div><div class="line">        List&lt;E&gt; list = (List&lt;E&gt;) tcm.getObject(cache, key);</div><div class="line">        <span class="keyword">if</span> (list == <span class="keyword">null</span>) &#123;</div><div class="line">            list = delegate.&lt;E&gt; query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);</div><div class="line">            tcm.putObject(cache, key, list); <span class="comment">// issue #578 and #116</span></div><div class="line">        &#125;</div><div class="line">        <span class="keyword">return</span> list;</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line"><span class="comment">// 委托基本执行器BaseExecutor去查询：</span></div><div class="line">    <span class="keyword">return</span> delegate.&lt;E&gt; query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="comment">// 二级缓存没有，就到BaseExecutor中查询</span></div><div class="line"><span class="meta">@Override</span></div><div class="line"><span class="keyword">public</span> &lt;E&gt; <span class="function">List&lt;E&gt; <span class="title">query</span><span class="params">(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler,</span></span></div><div class="line"><span class="function"><span class="params">        CacheKey key, BoundSql boundSql)</span> <span class="keyword">throws</span> SQLException </span>&#123;</div><div class="line">    ErrorContext.instance().resource(ms.getResource()).activity(<span class="string">"executing a query"</span>).object(ms.getId());</div><div class="line">    <span class="keyword">if</span> (closed) &#123;</div><div class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> ExecutorException(<span class="string">"Executor was closed."</span>);</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">if</span> (queryStack == <span class="number">0</span> &amp;&amp; ms.isFlushCacheRequired()) &#123;</div><div class="line">        clearLocalCache();</div><div class="line">    &#125;</div><div class="line">    List&lt;E&gt; list;</div><div class="line">    <span class="keyword">try</span> &#123;</div><div class="line">        queryStack++;</div><div class="line">        <span class="comment">// protected PerpetualCache localCache;</span></div><div class="line">        <span class="comment">// 从一级缓存中查询key，如果没有就调用queryFromDatabase去数据库查询</span></div><div class="line">        list = resultHandler == <span class="keyword">null</span> ? (List&lt;E&gt;) localCache.getObject(key) : <span class="keyword">null</span>;</div><div class="line">        <span class="keyword">if</span> (list != <span class="keyword">null</span>) &#123;</div><div class="line">            handleLocallyCachedOutputParameters(ms, key, parameter, boundSql);</div><div class="line">        &#125; <span class="keyword">else</span> &#123;</div><div class="line">            list = queryFromDatabase(ms, parameter, rowBounds, resultHandler, key, boundSql);</div><div class="line">        &#125;</div><div class="line">    &#125; <span class="keyword">finally</span> &#123;</div><div class="line">        queryStack--;</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">if</span> (queryStack == <span class="number">0</span>) &#123;</div><div class="line">        <span class="keyword">for</span> (DeferredLoad deferredLoad : deferredLoads) &#123;</div><div class="line">            deferredLoad.load();</div><div class="line">        &#125;</div><div class="line">        <span class="comment">// issue #601</span></div><div class="line">        deferredLoads.clear();</div><div class="line">        <span class="keyword">if</span> (configuration.getLocalCacheScope() == LocalCacheScope.STATEMENT) &#123;</div><div class="line">            <span class="comment">// issue #482</span></div><div class="line">            clearLocalCache();</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">return</span> list;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>从上面可以知道Session级别的一级缓存实际上就是使用PerpetualCache维护的，那么PerpetualCache是怎样实现的呢？</p>
<p>PerpetualCache实现原理其实很简单，其内部就是通过一个简单的HashMap<k,v> 来实现的，没有其他的任何限制。如下是PerpetualCache的实现代码：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">PerpetualCache</span> <span class="keyword">implements</span> <span class="title">Cache</span> </span>&#123;</div><div class="line">  <span class="keyword">private</span> String id;</div><div class="line">  <span class="keyword">private</span> Map&lt;Object, Object&gt; cache = <span class="keyword">new</span> HashMap&lt;Object, Object&gt;();</div><div class="line"><span class="comment">// ....</span></div></pre></td></tr></table></figure></k,v></p>
<h3 id="一级缓存的生命周期"><a href="#一级缓存的生命周期" class="headerlink" title="一级缓存的生命周期"></a>一级缓存的生命周期</h3><p>1、MyBatis在开启一个数据库会话时，会 创建一个新的SqlSession对象，SqlSession对象中会有一个新的Executor对象，Executor对象中持有一个新的PerpetualCache对象；当会话结束时，SqlSession对象及其内部的Executor对象还有PerpetualCache对象也一并释放掉。</p>
<p>2、如果SqlSession调用了close()方法，会释放掉一级缓存PerpetualCache对象，一级缓存将不可用。</p>
<p>3、如果SqlSession调用了clearCache()，会清空PerpetualCache对象中的数据，但是该对象仍可使用。</p>
<p>4、SqlSession中执行了任何一个update操作(update()、delete()、insert())，都会清空PerpetualCache对象的数据，但是该对象可以继续使用。</p>
<h3 id="CacheKey的hashcode生成算法"><a href="#CacheKey的hashcode生成算法" class="headerlink" title="CacheKey的hashcode生成算法"></a>CacheKey的hashcode生成算法</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">doUpdate</span><span class="params">(Object object)</span> </span>&#123;  </div><div class="line">   <span class="comment">//1. 得到对象的hashcode;    </span></div><div class="line">   <span class="keyword">int</span> baseHashCode = object == <span class="keyword">null</span> ? <span class="number">1</span> : object.hashCode();  </div><div class="line">   <span class="comment">//对象计数递增  </span></div><div class="line">   count++;  </div><div class="line">   checksum += baseHashCode;  </div><div class="line">   <span class="comment">//2. 对象的hashcode 扩大count倍  </span></div><div class="line">   baseHashCode *= count;  </div><div class="line">   <span class="comment">//3. hashCode * 拓展因子（默认37）+拓展扩大后的对象hashCode值  </span></div><div class="line">   hashcode = multiplier * hashcode + baseHashCode;  </div><div class="line">   updateList.add(object);  </div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h3 id="使用一级缓存需要注意的问题"><a href="#使用一级缓存需要注意的问题" class="headerlink" title="使用一级缓存需要注意的问题"></a>使用一级缓存需要注意的问题</h3><p>1、对于数据变化频率很大，并且需要高时效准确性的数据要求，我们使用SqlSession查询的时候，要控制好SqlSession的生存时间，SqlSession的生存时间越长，它其中缓存的数据有可能就越旧，从而造成和真实数据库的误差；同时对于这种情况，用户也可以手动地适时清空SqlSession中的缓存。</p>
<p>2、对于只执行、并且频繁执行大范围的select操作的SqlSession对象，SqlSession对象的生存时间不应过长。</p>
<p>3、MyBatis认为的完全相同的查询，不是指使用sqlSession查询时传递给算起来Session的所有参数值完完全全相同，你只要保证statementId，rowBounds,最后生成的SQL语句，以及这个SQL语句所需要的参数完全一致就可以了。</p>

        </div>

        <blockquote class="post-copyright">
    <div class="content">
        
<span class="post-time">
    最后更新时间：<time datetime="2017-12-05T10:18:12.988Z" itemprop="dateUpdated">2017年12月5日 18:18</time>
</span><br>


        如要转载请注明出处：<a href="/2017/08/15/Mybatis_primary_06/" target="_blank" rel="external">http://magic_duck.oschina.io/2017/08/15/Mybatis_primary_06/</a>
    </div>
    <footer>
        <a href="http://magic_duck.oschina.io">
            <img src="/img/avatar.jpg" alt="神奇的鸭鸭">
            神奇的鸭鸭
        </a>
    </footer>
</blockquote>

        
<div class="page-reward">
    <a id="rewardBtn" href="javascript:;" class="page-reward-btn waves-effect waves-circle waves-light">赏</a>
</div>



        <div class="post-footer">
            
	<ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/SSM/">SSM</a></li></ul>


            
<div class="page-share-wrap">
    

<div class="page-share" id="pageShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://magic_duck.oschina.io/2017/08/15/Mybatis_primary_06/&title=《Mybatis快速入门六(一级缓存)》 — 神奇的鸭鸭の码农库&pic=http://magic_duck.oschina.io/img/avatar.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://magic_duck.oschina.io/2017/08/15/Mybatis_primary_06/&title=《Mybatis快速入门六(一级缓存)》 — 神奇的鸭鸭の码农库&source=" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://magic_duck.oschina.io/2017/08/15/Mybatis_primary_06/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《Mybatis快速入门六(一级缓存)》 — 神奇的鸭鸭の码农库&url=http://magic_duck.oschina.io/2017/08/15/Mybatis_primary_06/&via=http://magic_duck.oschina.io" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://magic_duck.oschina.io/2017/08/15/Mybatis_primary_06/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>



    <a href="javascript:;" id="shareFab" class="page-share-fab waves-effect waves-circle">
        <i class="icon icon-share-alt icon-lg"></i>
    </a>
</div>



        </div>
    </div>

    
<nav class="post-nav flex-row flex-justify-between">
  
    <div class="waves-block waves-effect prev">
      <a href="/2017/08/15/Mybatis_primary_07/" id="post-prev" class="post-nav-link">
        <div class="tips"><i class="icon icon-angle-left icon-lg icon-pr"></i> Prev</div>
        <h4 class="title">Mybatis快速入门七(二级缓存)</h4>
      </a>
    </div>
  

  
    <div class="waves-block waves-effect next">
      <a href="/2017/08/14/Mybatis_primary_05/" id="post-next" class="post-nav-link">
        <div class="tips">Next <i class="icon icon-angle-right icon-lg icon-pl"></i></div>
        <h4 class="title">Mybatis快速入门五(关联查询映射)</h4>
      </a>
    </div>
  
</nav>



    







</article>

<div id="reward" class="page-modal reward-lay">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <h3 class="reward-title">
        <i class="icon icon-quote-left"></i>
        我只要一角钱~ ~
        <i class="icon icon-quote-right"></i>
    </h3>
    <ul class="reward-items">
        
        <li>
            <img src="/img/wechat.png" title="微信打赏二维码" alt="微信打赏二维码">
            <p>微信</p>
        </li>
        

        
        <li>
            <img src="/img/alipay.jpg" title="支付宝打赏二维码" alt="支付宝打赏二维码">
            <p>支付宝</p>
        </li>
        
    </ul>
</div>



</div>

        <footer class="footer">
    <div class="top">
        
<p>
    <span id="busuanzi_container_site_uv" style='display:none'>
        站点总访客数：<span id="busuanzi_value_site_uv"></span>
    </span>
    <span id="busuanzi_container_site_pv" style='display:none'>
        站点总访问量：<span id="busuanzi_value_site_pv"></span>
    </span>
</p>


        <p>
            <span><a href="" target="_blank" class="rss" title="rss"><i class="icon icon-lg icon-rss"></i></a></span>
            <span>博客内容遵循 <a href="http://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">知识共享 署名 - 非商业性 - 相同方式共享 4.0协议</a></span>
        </p>
    </div>
    <div class="bottom">
        <p>
            <span>Power by <a href="http://hexo.io/" target="_blank">Hexo</a> Theme <a href="https://git.oschina.net/z77z" target="_blank">邹海清</a></span>
            <span>神奇的鸭鸭の码农库 &copy; 2017</span>
        </p>
    </div>
</footer>

    </main>
    <div class="mask" id="mask"></div>
<a href="javascript:;" id="gotop" class="waves-effect waves-circle waves-light"><span class="icon icon-lg icon-chevron-up"></span></a>



<div class="global-share" id="globalShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://magic_duck.oschina.io/2017/08/15/Mybatis_primary_06/&title=《Mybatis快速入门六(一级缓存)》 — 神奇的鸭鸭の码农库&pic=http://magic_duck.oschina.io/img/avatar.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://magic_duck.oschina.io/2017/08/15/Mybatis_primary_06/&title=《Mybatis快速入门六(一级缓存)》 — 神奇的鸭鸭の码农库&source=" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://magic_duck.oschina.io/2017/08/15/Mybatis_primary_06/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《Mybatis快速入门六(一级缓存)》 — 神奇的鸭鸭の码农库&url=http://magic_duck.oschina.io/2017/08/15/Mybatis_primary_06/&via=http://magic_duck.oschina.io" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://magic_duck.oschina.io/2017/08/15/Mybatis_primary_06/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>


<div class="page-modal wx-share" id="wxShare">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <p>扫一扫，分享到微信</p>
    <img src="//api.qrserver.com/v1/create-qr-code/?data=http://magic_duck.oschina.io/2017/08/15/Mybatis_primary_06/" alt="微信分享二维码">
</div>




    <script src="//cdn.bootcss.com/node-waves/0.7.4/waves.min.js"></script>
<script>
var BLOG = { ROOT: '/', SHARE: true, REWARD: true };



lazyScripts.push('//s95.cnzz.com/z_stat.php?id=1261081671&web_id=1261081671')

</script>

<script src="/js/main.min.js?v=1.4.3"></script>


<div class="search-panel" id="search-panel">
    <ul class="search-result" id="search-result"></ul>
</div>
<template id="search-tpl">
<li class="item">
    <a href="{path}" class="waves-block waves-effect">
        <div class="title ellipsis" title="{title}">{title}</div>
        <div class="flex-row flex-middle">
            <div class="tags ellipsis">
                {tags}
            </div>
            <time class="flex-col time">{date}</time>
        </div>
    </a>
</li>
</template>

<script src="/js/search.min.js?v=1.4.3" async></script>






<script async src="//dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>


</body>
</html>
